<template>
  <el-card class="box-card ascd">
    <template #header>
      <div class="card-header">
        <ArrowLeftBold class="back" @click="back" />
        <span>{{ title == 'add' ? '新增网点' : '编辑网点' }}</span>
      </div>
    </template>

    <div class="form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder=""
            style="width: 280px"
          />
        </el-form-item>
        <el-row class="flex-form-item">
          <el-form-item prop="province" label="地址" style="width: 300px">
            <el-select
              v-model="ruleForm.province"
              placeholder="请选择省"
              @change="changeProvince"
              clearable
            >
              <el-option
                v-for="item in PCA.address"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="city" style="width: 220px">
            <el-select
              v-model="ruleForm.city"
              placeholder="请选择市"
              @change="changeCity"
              clearable
            >
              <el-option
                v-for="item in cityList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="area" style="width: 220px">
            <el-select
              v-model="ruleForm.area"
              placeholder="请选择区"
              :disabled="false"
              clearable
            >
              <el-option
                v-for="item in areaList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="street" style="width: 300px">
            <el-input
              v-model="ruleForm.street"
              clearable
              placeholder="街道门牌号"
            />
          </el-form-item>
        </el-row>

        <el-form-item label="电话" prop="mobile">
          <div class="phonBox">
            <el-input
              v-model="ruleForm.mobile"
              placeholder=""
              style="width: 280px"
            />
            <span>只限单个联系方式</span>
          </div>
        </el-form-item>

        <el-form-item label="图片" prop="image">
          <ImageUpload
            :limit="5"
            :modelValue="modelValueList"
            @update:modelValue="modelValue"
          ></ImageUpload>
        </el-form-item>

        <el-form-item label="服务类型" prop="type">
          <el-checkbox-group v-model="ruleForm.type">
            <el-checkbox
              v-for="item in checkedCities"
              :label="item.id"
              :key="item.id"
              :value="item.name"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="简介" prop="blurb">
          <el-input
            style="width: 787px"
            v-model="ruleForm.blurb"
            :rows="4"
            type="textarea"
          />
        </el-form-item>

        <el-form-item>
          <el-button class="btn" type="primary" @click="submitForm(ruleFormRef)"
            >保存</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { servece, serveceInfo } from '@/api/sericeNetwork/index';
// import provinces from "./provinces.vue"
const loading = ref(false);
import PCA from './area.json';
const cityList = ref([]);
const areaList = ref([]);
const router = useRouter();
const route = useRoute();
const ruleFormRef = ref();
const title = ref('');
const modelValueList = ref([]);
const checkedCities = reactive([
  {
    id: '1',
    name: '志愿填报',
  },
  {
    id: '2',
    name: '心理咨询',
  },
  {
    id: '3',
    name: '综合评估',
  },
  {
    id: '4',
    name: '学前辅导',
  },
  {
    id: '5',
    name: '家庭教育',
  },
]);
const ruleForm = reactive({
  id: 0,
  name: '',
  province: '',
  city: '',
  area: '',
  street: '',
  mobile: '',
  image: '',
  type: [],
  blurb: '',
});

const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  province: [{ required: true, message: '请选择省', trigger: 'blur' }],
  city: [{ required: true, message: '请选择市', trigger: 'blur' }],
  area: [{ required: true, message: '请选择区', trigger: 'blur' }],
  street: [{ required: true, message: '请填写街道门牌号', trigger: 'blur' }],
  mobile: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  image: [{ required: true, message: '请上传图片', trigger: 'blur' }],
  type: [{ required: true, message: '请选择一个', trigger: 'blur' }],
});
// 省
const changeProvince = (val) => {
  cityList.value = [];
  areaList.value = [];
  ruleForm.city = '';
  ruleForm.area = '';
  ruleForm.province = val;
  cityList.value = PCA.address.filter((item) => item.code == val);
  if (cityList.value[0]) {
    cityList.value = cityList.value[0].children;
  }
};
// 市
const changeCity = (val) => {
  areaList.value = [];
  ruleForm.area = '';
  ruleForm.city = val;
  areaList.value = cityList.value.filter((item) => item.code == val);
  if (areaList.value[0]) {
    areaList.value = areaList.value[0].children;
  }
};
const modelValue = (val) => {
  ruleForm.image = val; // 保存单张图片
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  try {
    await formEl.validate((valid) => {
      if (valid) {
        loading.value = true;
        servece(ruleForm).then((res) => {
          if (res.code === 20000) {
            ElMessage({
              message: res.msg,
              type: 'success',
            });
          }
        });
      }
    });
  } finally {
    loading.value = false;
    router.push({ path: 'serviceSite' });
  }
};

const back = () => {
  router.push({ path: 'serviceSite' });
};
const getDetail = async (id) => {
  try {
    loading.value = true;
    const { data } = await serveceInfo({ id });
    modelValueList.value = data.image;
    cityList.value = PCA.address
      .map((item) => item.children)
      .flat() // 展平数组，因为 map 之后的结果是嵌套数组
      .filter((child) => child.code === data.city);
    if (cityList.value[0]) {
      areaList.value = cityList.value[0].children.filter(
        (item) => item.code === data.area
      );
    }
    Object.assign(ruleForm, data);
  } finally {
    loading.value = false;
  }
};
onMounted(() => {
  if (route.query.name == 'add') {
    title.value = route.query.name;
  } else {
    getDetail(route.query.id);
  }
});
</script>
<style lang="scss" scoped>
.box-card {
  margin: 20px;

  .back {
    width: 1em;
    height: 1em;
    margin-right: 8px;
    cursor: pointer;
  }

  .card-header {
    display: flex;
    align-items: center;
  }

  .phonBox {
    display: flex;
    align-items: center;

    span {
      color: rgb(164, 164, 164);
      display: inline-block;
      margin-left: 10px;
    }
  }

  .btn {
    background-color: #165dff;
    border-color: #165dff;
    width: 170px;
  }
}
</style>
<style lang="scss">
.ascd .flex-form-item {
  .el-form-item__content {
    margin-left: 5px !important;
  }
}
</style>
